package com.mobi.Survey.lib.activities;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import com.mobi.Survey.lib.R;
import com.mobi.Survey.lib.db.SurveyTable;
import com.mobi.Survey.lib.exceptions.AuthenticationException;
import com.mobi.Survey.lib.model.SurveyPojo;
import com.mobi.Survey.lib.model.SurveysJsonParser;
import com.mobi.Survey.lib.utils.Helper;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SplashScreen.java Responsible for Displaying Splash Screen for
 * {@link #SPLASH_DISPLAY_TIME} milli secconds
 * <p>
 */
public class SplashScreen extends AbstractScreen {

	private int SPLASH_DISPLAY_TIME = 1000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		Helper.createDirIfNotExists(Helper.APP_FOLDER);

		Handler handler = new Handler();

		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				String hardCodedUserId = getString(R.string.hardcoded_user_id);
				String hardCodedPsw = getString(R.string.hardcoded_psw);
				if (isAutoLoadId(SplashScreen.this)) {
					hardCodedPsw = "";
					//hardCodedPsw = getPasswordFromPreferences();
					hardCodedUserId = getAutoLoadUserId(SplashScreen.this);
					

				}

				if (null == hardCodedUserId
						|| hardCodedUserId.trim().length() == 0
						|| !Helper.isNetworkAvailable(SplashScreen.this)) {
					switchToLoginScreen();
					finish();
				} else {
					saveCredentials(hardCodedUserId.trim(), hardCodedPsw,
							SplashScreen.this);
					if (isAutoLoadId(SplashScreen.this)) {
						SurveyTable st = new SurveyTable(SplashScreen.this);
						int count =  st.getSurveyCountByUserId(hardCodedUserId);
						st.closeDB();
						if(count>0){
							getUserPrefrences();
							populateUserBitmaps(false);
							switchToSurveyScreen();
							finish();
						}else{
							new SurveyDownloadTask().execute(hardCodedUserId,
									hardCodedPsw);
						}
					}else{
						new SurveyDownloadTask().execute(hardCodedUserId,
								hardCodedPsw);
					}
				

				}
			}
		}, SPLASH_DISPLAY_TIME);

	}

	public class SurveyDownloadTask extends AsyncTask<String, Integer, Integer> {
		private final int LOGIN_ERROR = 0;

		private static final int SWITCH_SCREEN = 1;

		private static final int NO_INTERNET_CONNECTION = 2;

		private static final int CONNECT_ERROR = 3;
		private static final int DEFAULT = 4;

		private String userId;

		private String psw = "";

		ProgressDialog progressDialog = null;

		protected Integer doInBackground(String... params) {
			if (isCancelled()) {
				return DEFAULT;
			}
			if (Helper.isNetworkAvailable(SplashScreen.this
					.getApplicationContext())) {
				userId = params[0];
				psw = params[1];

				try {
					String surveyHeaderUrl = getString(
							R.string.survey_list_headers_url, userId, psw);

					InputStream loginResponse = Helper
							.performGetOperationI(surveyHeaderUrl);

					List<SurveyPojo> surveys = SurveysJsonParser.getInstance()
							.isUser(loginResponse);
					publishProgress(30);

					if (surveys.size() > 0) {
						SurveyPojo.deleteAll(getApplicationContext());
						publishProgress(40);
						SurveyPojo.commitAll(getApplicationContext(), surveys,userId);

					}

					populateUserBitmaps(true);

					return SWITCH_SCREEN;

				} catch (AuthenticationException ex) {
					return LOGIN_ERROR;
				}

				catch (IOException e) {
					return CONNECT_ERROR;
				} catch (Exception e) {

					return CONNECT_ERROR;
				}

			} else {
				return NO_INTERNET_CONNECTION;
			}

		}

		@Override
		protected void onProgressUpdate(Integer... values) {

			super.onProgressUpdate(values);

			if (values[0] == 30) {
				progressDialog.setMessage(Messages.DOWNLOADING_SURVEYS);
			}
			if (values[0] == 40) {
				progressDialog.setMessage(Messages.UPDATING_DATABASE);
			}
		}

		protected void onPostExecute(Integer result) {

			super.onPostExecute(result);

			progressDialog.dismiss();
			progressDialog = null;
			finish();
			switch (result) {

			case LOGIN_ERROR:

				switchToLoginScreen();
				break;
			case CONNECT_ERROR:

			case NO_INTERNET_CONNECTION:
				getUserPrefrences();
				switchToSurveyScreen();
				finish();

				break;

			case SWITCH_SCREEN:
				setUserPrefrences();
				switchToSurveyScreen();

				break;

			}

		}

		protected void onPreExecute() {

			super.onPreExecute();

			progressDialog = ProgressDialog.show(SplashScreen.this, "",
					Messages.LOGGIN_IN);

		}

	}

	protected void switchToSurveyScreen() {
		switchScreenTo(SurveyListScreen.class);
	}

	protected void switchToLoginScreen() {

		switchScreenTo(LoginScreen.class);

	}

	@Override
	protected void initUiVars() {

	}

	@Override
	protected int getLayoutId() {

		return LayoutIds.SPLASH_SCREEN;
	}

	@Override
	protected void onRelease() {
		finish();
	}

}
